package com.ellecity06.cwhiskymall.ui.calssify

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.QuickAdapterHelper
import com.chad.library.adapter.base.loadState.LoadState
import com.chad.library.adapter.base.loadState.trailing.TrailingLoadStateAdapter
import com.ellecity06.common.adapter.CustomLoadMoreAdapter
import com.ellecity06.common.base.BaseMvvmFragment
import com.ellecity06.common.ktx.finishRefresh
import com.ellecity06.common.ktx.launchActivity
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.adapter.ClassifyLeftAdapter
import com.ellecity06.cwhiskymall.adapter.ClassifyRightAdapter
import com.ellecity06.cwhiskymall.adapter.ClassifyTopAdapter
import com.ellecity06.cwhiskymall.bean.response.ClassifyChildren
import com.ellecity06.cwhiskymall.bean.response.ClassifyResponse
import com.ellecity06.cwhiskymall.databinding.FragmentClassifyBinding
import com.ellecity06.cwhiskymall.ui.search.SearchActivity
import com.ellecity06.cwhiskymall.ui.webview.WebHelper
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/10/22 14:53
 * @des 分类
 */
class ClassifyFragment : BaseMvvmFragment<FragmentClassifyBinding, ClassifyViewModel>(),
    TrailingLoadStateAdapter.OnTrailingListener, View.OnClickListener {
    private val topAdapter: ClassifyTopAdapter by lazy { ClassifyTopAdapter() }
    private val leftAdapter: ClassifyLeftAdapter by lazy { ClassifyLeftAdapter() }
    private val rightAdapter: ClassifyRightAdapter by lazy { ClassifyRightAdapter() }
    private var mClassifyId = -1
    private var topCheck = 0
    private var topCheckId = -1

    companion object {
        @JvmStatic
        fun newInstance(): ClassifyFragment {
            return ClassifyFragment()
        }

    }

    override fun lazyInit() {
        getDataIntent()
        observeViewModel()
    }

    private lateinit var adapterHelper: QuickAdapterHelper

    override fun initView() {
        super.initView()
        binding.rvClassifyTop.apply {
            layoutManager = LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false)
            adapter = topAdapter
        }
        binding.rvClassifyLeft.apply {
            layoutManager = LinearLayoutManager(requireActivity())
            adapter = leftAdapter
        }

        val layoutManager = LinearLayoutManager(requireActivity())
        binding.rvClassifyRight.layoutManager = layoutManager

        val loadMoreAdapter = CustomLoadMoreAdapter()
        loadMoreAdapter.setOnLoadMoreListener(this)
        rightAdapter.animationEnable = true
        rightAdapter.setItemAnimation(BaseQuickAdapter.AnimationType.ScaleIn)
        adapterHelper = QuickAdapterHelper.Builder(rightAdapter)
            .setTrailingLoadStateAdapter(loadMoreAdapter)
            .build()

        binding.rvClassifyRight.adapter = adapterHelper.adapter
        binding.refreshLayout.setOnRefreshListener {
            rightAdapter.submitList(emptyList())
            refreshTopAndData()
        }

        topAdapter.setOnItemClickListener { _, _, position ->
            topCheckId = topAdapter.getItem(position)?.id ?: -1
            topCheck = position
            topAdapter.notifyPos(position)
            lifecycleScope.launch {
                viewModel.intentChannel.send(
                    ClassifyIntent.getLeftCatetoryList(
                        topAdapter.getItem(
                            position
                        )?.id ?: -1
                    )
                )
            }
        }
        leftAdapter.setOnItemClickListener { _, _, position ->
            leftAdapter.notifyPos(position)
            rightAdapter.submitList(emptyList())
            mClassifyId = leftAdapter.getItem(position)?.id ?: -1
            refreshData()
        }
        binding.btnExpand.setOnClickListener {
            lifecycleScope.launch {
                viewModel.intentChannel.send(ClassifyIntent.showDialog)
            }
        }
        rightAdapter.setOnItemClickListener { _, _, position ->
            val item = rightAdapter.getItem(position)
            WebHelper.goodDetails(requireActivity(), item?.id ?: 0)
        }
        binding.layoutSearch.setOnClickListener(this)
    }

    private fun refreshTopAndData() {
        getDataIntent()
    }

    override fun inflateBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentClassifyBinding {
        return FragmentClassifyBinding.inflate(inflater, container, false)
    }

    private fun getDataIntent() {
        lifecycleScope.launch {
            viewModel.intentChannel.send(ClassifyIntent.getCagetoryList)
        }
    }

    private fun setTopData(data: List<ClassifyResponse>) {
        topAdapter.submitList(data)
    }

    private fun setLeftData(data: List<ClassifyChildren>) {
        leftAdapter.submitList(data)
        rightAdapter.submitList(emptyList())
        if (data.isNotEmpty()) {
            var pos = 0
            if (mClassifyId != -1) {
                val positions =
                    data.withIndex().filter { d -> d.value.id == mClassifyId }.map { i -> i.index }
                if (positions.isNotEmpty()) {
                    pos = positions[0]
                }
            }
            leftAdapter.notifyPos(pos)
            mClassifyId = data[pos].id
            refreshData()
        } else {
            mClassifyId = -1
            adapterHelper.trailingLoadState = LoadState.NotLoading(true)
        }
    }

    fun checkTop(id: Int) {
        topCheckId= id
        if (topAdapter.items.isEmpty()) return
        val filter = topAdapter.items.filter { it.id == id }
        if (filter.isNotEmpty()) {
            val classifyResponse = filter[0]

            val itemPosition = topAdapter.getItemPosition(classifyResponse)
            topCheck = itemPosition

            topAdapter.notifyPos(itemPosition)
            lifecycleScope.launch {
                viewModel.intentChannel.send(
                    ClassifyIntent.getLeftCatetoryList(
                        classifyResponse.id
                    )
                )
            }
            binding.rvClassifyTop.smoothScrollToPosition(itemPosition)
        } else {
            val classifyResponse = topAdapter.items[0]
            val itemPosition = topAdapter.getItemPosition(classifyResponse)
            topCheck = itemPosition
            topAdapter.notifyPos(itemPosition)
            lifecycleScope.launch {
                viewModel.intentChannel.send(
                    ClassifyIntent.getLeftCatetoryList(
                        classifyResponse.id
                    )
                )
            }
            binding.rvClassifyTop.smoothScrollToPosition(itemPosition)
        }


    }

    fun loadMoreData() {
        lifecycleScope.launch {
            viewModel.intentChannel.send(ClassifyIntent.getClassifyRightList(true, mClassifyId))
        }
    }

    fun refreshData() {
        lifecycleScope.launch {
            adapterHelper.trailingLoadState = LoadState.None
            viewModel.intentChannel.send(ClassifyIntent.getClassifyRightList(false, mClassifyId))
        }
    }

    private fun observeViewModel() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is ClassifyState.ClassifyTopData -> {
                    binding.refreshLayout.finishRefresh()
                    setTopData(it.data)
                    if (topCheckId != -1) {
                        val positions = it.data.withIndex().filter { d -> d.value.id == topCheckId }
                            .map { i -> i.index }
                        if (positions.isNotEmpty()) {
                            topCheck = positions[0]
                            topAdapter.notifyPos(topCheck)
                            try {
                                binding.rvClassifyTop.smoothScrollToPosition(topCheck)
                            }catch (e:Exception){
                                e.printStackTrace()
                            }

                        }
                    }
                    if (it.data.isNotEmpty()) {
                        lifecycleScope.launch {
                            viewModel.intentChannel.send(ClassifyIntent.getLeftCatetoryList(it.data[topCheck].id))
                        }
                    }
                }
                is ClassifyState.ClassifyLeftData -> {
                    setLeftData(it.data)
                }
                is ClassifyState.RefreshGoods -> {
                    rightAdapter.submitList(it.list)
                    adapterHelper.trailingLoadState = LoadState.NotLoading(!it.hasMore)
                    binding.refreshLayout.finishRefresh()
                }
                is ClassifyState.LoadMoreGoods -> {
                    rightAdapter.addAll(it.list)
                    adapterHelper.trailingLoadState = LoadState.NotLoading(!it.hasMore)
                }
                is ClassifyState.Error -> {
                    binding.refreshLayout.finishRefresh()
                }
                is ClassifyState.noMoreData -> {
                    binding.refreshLayout.finishRefresh()
                    adapterHelper.trailingLoadState = LoadState.NotLoading(true)
                }
                is ClassifyState.showDialog -> {
                    var list = ArrayList<ClassifyResponse>()
                    list.addAll(it.data!!)
                    var dialog = ClassifyDialog.newInstance(
                        topCheck,
                        list,
                        object : ClassifyDialog.OnCheckListener {
                            override fun check(pos: Int) {
                                topCheck = pos
                                topAdapter.notifyPos(pos)
                                binding.rvClassifyTop.scrollToPosition(pos)
                                lifecycleScope.launch {
                                    viewModel.intentChannel.send(
                                        ClassifyIntent.getLeftCatetoryList(
                                            topAdapter.getItem(pos)?.id ?: -1
                                        )
                                    )
                                }
                            }
                        })
                    dialog.show(requireActivity())

                }
            }
        }
    }

    override fun onFailRetry() {
    }

    override fun onLoad() {
        if (mClassifyId != -1) {
            loadMoreData()
        }
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            binding.layoutSearch.id -> {
                launchActivity<SearchActivity>()
            }
        }
    }
}